package com.wangzhixuan.apiController;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.sun.tools.apt.Main;
import com.wangzhixuan.commons.base.ApiBaseController;
import com.wangzhixuan.commons.constant.ApiCode;
import com.wangzhixuan.commons.scan.MyException;
import com.wangzhixuan.commons.utils.MethodUtil;
import com.wangzhixuan.commons.utils.PictureNarrowUtil;
import com.wangzhixuan.model.Skydrive;
import com.wangzhixuan.model.User;
import com.wangzhixuan.model.vo.CloudUpLoadVo;
import com.wangzhixuan.service.IHistoryService;
import com.wangzhixuan.service.ISkydriveService;
import com.wangzhixuan.service.IUserService;



/**
 * <p>
 *   前端控制器
 * </p>
 * @author zhixuan.wang
 * @since 2017-08-24
 */
@Controller
@RequestMapping("/api")
public class CloudDiskUploadApiController extends ApiBaseController{

    @Autowired private ISkydriveService skydriveService;
    
    @Autowired private IHistoryService historyService;
	
    @Autowired private IUserService userService;
	@RequestMapping("/file/add")
	@ResponseBody
	public Object fileUpload(@RequestParam("fileDetailsArr") CommonsMultipartFile[] fileDetailsArr,
			HttpServletRequest request, HttpServletResponse response,
			Integer userId,Integer fileId)throws Exception {
    	if (userId == null  ) {
			throw new MyException(ApiCode.CODE_501, "请重新登录");
		}
		if (fileId == null) {
			throw new MyException(ApiCode.CODE_501, "网络异常，请稍后重试");
		}
    	Skydrive pSkydrive = skydriveService.selectById(fileId);
    	if(pSkydrive==null){
    		throw new MyException(ApiCode.CODE_500, "父文件夹不存在，不能上传文件");
    	}
    	if(pSkydrive.getIsShare()==1&&pSkydrive.getCreateId()!=userId){
    		if(fileId!=305){
    			return renderError(ApiCode.CODE_500, "您没有操作此文件夹的权限"); 
    		}
    	}
		for(MultipartFile myfile : fileDetailsArr){
        	if(myfile.isEmpty()){  
        		return renderError(ApiCode.CODE_1501, "请选择文件后上传"); 
        	}
        }
		List<CloudUpLoadVo> list = saveFiles(fileDetailsArr, request,userId,fileId,pSkydrive);
		return renderSuccess(ApiCode.CODE_200, "上传成功",list);
	}


	
	private List<CloudUpLoadVo> saveFiles(MultipartFile[] myfiles, HttpServletRequest request,
			Integer userId,Integer fileId,Skydrive pSkydrive)
			throws Exception, IOException {
		String pathRoot = getRootPath();
		String filePath = mkdirs(pathRoot,userId);
		new File(filePath).mkdirs();
		List<String> list = new ArrayList<String>();
		Skydrive skydrive = new Skydrive();
		Date date = new Date();
		List<CloudUpLoadVo> cloudUpLoadVoList = new ArrayList<CloudUpLoadVo>();
		SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmssSSS");
		for(MultipartFile myfile : myfiles){
			Date date2 = new Date();
			Integer flag = 1;
			//System.out.println(myfile.getOriginalFilename());
			skydrive.setSmallPictureUrl("");                                    //=========先设置缩略图为""=======//
			String Filename = myfile.getOriginalFilename();
			String tempfilePath = filePath + Filename;
			String format4 = format.format(date2);
			File fileUpload = new File(pathRoot + filePath+"_"+format4+myfile.getOriginalFilename().substring(          //获得后缀名
					myfile.getOriginalFilename().lastIndexOf(".")));
			String fileSuffixName = myfile.getOriginalFilename().substring(          //获得后缀名
			myfile.getOriginalFilename().lastIndexOf("."));
			if(fileSuffixName.equals(".abc")){									//.abc为自定义的缩略图后缀名
				String nameOfFile = Filename.substring(0, myfile.getOriginalFilename().lastIndexOf("."));
				String newName = MethodUtil.MD5(nameOfFile)+".PNG";									//后缀.abc改成PNG
				String newUrl = pathRoot+filePath+newName;
				File newUpLoad = new File(newUrl);
				myfile.transferTo(newUpLoad);
				continue;													//跳出当前循环，不执行数据添加
			}
			/*if(fileUpload.exists()){
				if(fileSuffixName.equals(".avi")||fileSuffixName.equals(".rmvb")||fileSuffixName.equals(".rm")||fileSuffixName.equals(".asf")||fileSuffixName.equals(".divx")||
						fileSuffixName.equals(".mpg")||fileSuffixName.equals(".mpeg")||fileSuffixName.equals(".mpe")||fileSuffixName.equals(".wmv")||fileSuffixName.equals(".mp4")||
						fileSuffixName.equals(".mkv")||fileSuffixName.equals(".vob")||fileSuffixName.equals(".mov")||fileSuffixName.equals(".AVI")||fileSuffixName.equals(".RMVB")||
						fileSuffixName.equals(".RM")||fileSuffixName.equals(".ASF")||fileSuffixName.equals(".DIVX")||fileSuffixName.equals(".MPG")||fileSuffixName.equals(".MPEG")||
						fileSuffixName.equals(".MPE")||fileSuffixName.equals(".WMV")||fileSuffixName.equals(".MP4")||fileSuffixName.equals(".MKV")||fileSuffixName.equals(".VOB")||
						fileSuffixName.equals(".MOV")){
					skydrive.setSmallPictureUrl(getbaseUrl(request)+filePath+MethodUtil.MD5(Filename.substring(0, myfile.getOriginalFilename().lastIndexOf(".")))+".PNG");
					flag = 0;
				}
				String format2 = format.format(date2);
				Filename =  Filename.substring(0, myfile.getOriginalFilename().lastIndexOf("."))+"_"+format2+myfile.getOriginalFilename().substring(          //获得后缀名
						myfile.getOriginalFilename().lastIndexOf("."));
				tempfilePath = filePath + Filename;
				fileUpload = new File(pathRoot + filePath+"_"+format2+myfile.getOriginalFilename().substring(          //获得后缀名
						myfile.getOriginalFilename().lastIndexOf(".")));
			}*/																		//通过时间来设置URL 允许同名
			myfile.transferTo(fileUpload);											//=================================上传=========================
			String format3 = format.format(date2);
			String URL = getbaseUrl(request) + filePath+"_"+format3+myfile.getOriginalFilename().substring(          //获得后缀名
					myfile.getOriginalFilename().lastIndexOf("."));;				//获得URL
			if(flag==1){
				if(fileSuffixName.equals(".avi")||fileSuffixName.equals(".rmvb")||fileSuffixName.equals(".rm")||fileSuffixName.equals(".asf")||fileSuffixName.equals(".divx")||
						fileSuffixName.equals(".mpg")||fileSuffixName.equals(".mpeg")||fileSuffixName.equals(".mpe")||fileSuffixName.equals(".wmv")||fileSuffixName.equals(".mp4")||
						fileSuffixName.equals(".mkv")||fileSuffixName.equals(".vob")||fileSuffixName.equals(".mov")||fileSuffixName.equals(".AVI")||fileSuffixName.equals(".RMVB")||
						fileSuffixName.equals(".RM")||fileSuffixName.equals(".ASF")||fileSuffixName.equals(".DIVX")||fileSuffixName.equals(".MPG")||fileSuffixName.equals(".MPEG")||
						fileSuffixName.equals(".MPE")||fileSuffixName.equals(".WMV")||fileSuffixName.equals(".MP4")||fileSuffixName.equals(".MKV")||fileSuffixName.equals(".VOB")||
						fileSuffixName.equals(".MOV")){
						skydrive.setSmallPictureUrl(getbaseUrl(request)+filePath+MethodUtil.MD5(Filename.substring(0, myfile.getOriginalFilename().lastIndexOf(".")))+".PNG");
					}
			}
			if(fileSuffixName.equals(".JPG")||fileSuffixName.equals(".jpg")||fileSuffixName.equals(".png")||fileSuffixName.equals(".PNG")
					||fileSuffixName.equals(".BMP")||fileSuffixName.equals(".bmp")||fileSuffixName.equals(".wbmp")||fileSuffixName.equals(".jpeg")||
					fileSuffixName.equals(".JPEG")||fileSuffixName.equals(".WBMP")||fileSuffixName.equals(".GIF")||fileSuffixName.equals(".gif")){
				PictureNarrowUtil.zoomImage((pathRoot + filePath+"_"+format4+myfile.getOriginalFilename().substring(myfile.getOriginalFilename().lastIndexOf("."))),(pathRoot + filePath+"sml_"+MethodUtil.MD5(Filename))+myfile.getOriginalFilename().substring(          //获得后缀名
						myfile.getOriginalFilename().lastIndexOf(".")),160,284);  //缩略图
				String B = (pathRoot + filePath+"sml_"+MethodUtil.MD5(Filename))+myfile.getOriginalFilename().substring(          //获得后缀名
						myfile.getOriginalFilename().lastIndexOf("."));
				String A = (pathRoot + filePath+"_"+format4+myfile.getOriginalFilename().substring(myfile.getOriginalFilename().lastIndexOf(".")));
				String C = getbaseUrl(request)+filePath+"sml_"+ MethodUtil.MD5(Filename)+myfile.getOriginalFilename().substring(          //获得后缀名
						myfile.getOriginalFilename().lastIndexOf("."));
				skydrive.setSmallPictureUrl(getbaseUrl(request)+filePath+"sml_"+ MethodUtil.MD5(Filename)+myfile.getOriginalFilename().substring(          //获得后缀名
						myfile.getOriginalFilename().lastIndexOf("."))); // <====设置缩略图为
				System.out.println("A:"+(pathRoot + filePath+"_"+format4+myfile.getOriginalFilename().substring(myfile.getOriginalFilename().lastIndexOf("."))+",B:"+ pathRoot + filePath+"sml_"+MethodUtil.MD5(Filename)+",C"+getbaseUrl(request)+filePath+"sml_"+ MethodUtil.MD5(Filename)));
			}
			skydrive.setFileSuffixName(fileSuffixName);
			skydrive.setCreateId(userId);
			skydrive.setCreateTime(date);
			skydrive.setModifyTime(date);
			skydrive.setFileFullName(pSkydrive.getFileFullName()+">>>"+Filename);
			skydrive.setFileName(Filename);
			skydrive.setFileUrl(URL);
			skydrive.setIsForder(0);
			skydrive.setIsShare(pSkydrive.getIsShare());
			skydrive.setPid(fileId);
			skydrive.setUploadSize(myfiles.length);
			skydriveService.insert(skydrive);
			Integer id = skydrive.getId();
			CloudUpLoadVo cloudUpLoadVo = new CloudUpLoadVo();
			User user = userService.selectById(userId);
			String creator = user.getName();
			cloudUpLoadVo.setCreator(creator);
			cloudUpLoadVo.setFileId(id);
			cloudUpLoadVo.setCreatorID(userId);
			cloudUpLoadVo.setFileType(312);    //312代表文件//311代表文件夹
			cloudUpLoadVo.setFileTime(new Date());
			cloudUpLoadVo.setFileName(Filename);
			cloudUpLoadVo.setFileSuffixName(fileSuffixName);
			cloudUpLoadVo.setSmallPictureUrl(getbaseUrl(request)+filePath+"sml_"+Filename);
			cloudUpLoadVo.setFileUrl(URL);
			cloudUpLoadVoList.add(cloudUpLoadVo);
			list.add(URL);
			System.out.println(URL);
			System.out.println(getbaseUrl(request)+filePath+"sml_"+Filename);
		}
		return cloudUpLoadVoList;
	}

	private String mkdirs(String pathRoot,Integer userId) {
		Date date = new Date();
		StringBuffer path = new StringBuffer();
		path.append("CloudDisk/").append(new SimpleDateFormat("yyyy/MM/dd").format(date))
				.append("/Id_"+userId+"/");
		File f = new File(pathRoot + path.toString());
		if (!f.exists())
			f.mkdirs();
		return path.toString();
	}
	
	
	
}
